const { KEYUTIL, KJUR, hextob64, hextob64u } = require('jsrsasign');

const fs = require('fs');
Date.prototype.format = function(format) {
    var o = {
        "M+": this.getMonth() + 1, //month  
        "d+": this.getDate(), //day  
        "h+": this.getHours(), //hour  
        "m+": this.getMinutes(), //minute  
        "s+": this.getSeconds(), //second  
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter  
        "S": this.getMilliseconds() //millisecond  
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
const publicKey = fs.readFileSync("./cert/apiclient_cert.pem").toString();
const privateKey = fs.readFileSync("./cert/apiclient_key.pem").toString();
const random = function (start, end) {
    if (end) {
        return parseInt(Math.random() * (end - start + 1) + start);
    } else {
        return parseInt(Math.random() * (start + 1));
    }
};
const generateOrderNumber = function () {
    let now = new Date();
    return (new Date().format("yyyyMMddhhmmssS") + random(1000000,9999999)).padEnd(24,"0");
};
const sha256withRSA = function(message){
    
    const key = KEYUTIL.getKey(privateKey);
    // 创建 Signature 对象，设置签名编码算法
    const signature = new KJUR.crypto.Signature({ alg: 'SHA256withRSA' });
    // 初始化
    signature.init(key);
    // 传入待加密字符串
    signature.updateString(message);
    // 生成密文
    const originSign = signature.sign();
    const sign64 = hextob64(originSign);
    // console.log('sign base64 =======', sign64);
    // const sign64u = hextob64u(originSign);
    // console.log('sign base64u=======', sign64u);
    return sign64;
}

module.exports = {
    generateOrderNumber,
    sha256withRSA
}

// console.log(sha256withRSA("wx8888888888888888\n1414561699\n5K8264ILTKCH16CQ2502SI8ZNMTM67VS\nprepay_id=wx201410272009395522657a690389285100\n"))




